package net.sunofbeach.blog.utils;

import io.jsonwebtoken.Claims;
import net.sunofbeach.blog.pojo.User;

import java.util.HashMap;
import java.util.Map;

/**
 * 生成 token 载荷用户信息工具类
 *
 * @author bing_  @create 2021/11/28-21:01
 */
public class ClaimsUtils {

    public static final String ID = "id";
    public static final String USER_NAME = "user_name";
    public static final String ROLE = "role";
    public static final String AVATAR = "avatar";
    public static final String EMAIL = "email";
    public static final String SIGN = "sign";


    /**
     * 设置token
     * @param user
     * @return
     */
    public static Map<String, Object> sobUser2Claims(User user) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(ID, user.getId());
        claims.put(USER_NAME, user.getUsername());
        claims.put(ROLE, user.getRole());
        claims.put(AVATAR, user.getAvatar());
        claims.put(EMAIL, user.getEmail());
        claims.put(SIGN, user.getSign());
        return claims;
    }

    /**
     * 解析token
     * @param claims
     * @return
     */
    public static User claims2SobUser(Claims claims){
        User user = new User();
        String id = (String) claims.get(ID);
        user.setId(id);
        String username = (String) claims.get(USER_NAME);
        user.setUsername(username);
        String role = (String) claims.get(ROLE);
        user.setRole(role);
        String avatar = (String) claims.get(AVATAR);
        user.setAvatar(avatar);
        String email = (String) claims.get(EMAIL);
        user.setEmail(email);
        String sign = (String) claims.get(SIGN);
        user.setSign(sign);

        return user;
    }
}
